import os from 'os';
import path from 'path';
import fs from 'fs';
import { ipcMain } from 'electron';
import log from 'electron-log';
import Store from 'electron-store';
import { setPathMacId, setNewSyncTask, batchFailure } from './service';
import configManager from './config';
import { getUserDataPath } from './utils/getUserDataPath';

import getMAC from 'getmac';

const store = new Store({
  name: 'sync',
  cwd: getUserDataPath(),
});

// eslint-disable-next-line import/prefer-default-export
export function DownloadSync({ port }) {
  let user = store.get('user');
  ipcMain.on('file:download', async (_event, data) => {
    const params: any = {
      busId: data.busId,
      mid: user.mid,
      downloadType: data.downloadType,
      fileId: data.fileId,
      nodeId: data.nodeId,
      mainId: store.get('mainId'),
      syncType: 1,
      pjId: data.pjId,
      coId: user.coId,
    };

    log.info({ params });

    setNewSyncTask(params)
      // eslint-disable-next-line promise/always-return
      .then((res) => {
        // eslint-disable-next-line promise/always-return
        if (res.success) {
          // 先创建目录

          const { dirsToBeCreated } = res.data;
          log.info({ dirsToBeCreated });

          dirsToBeCreated.forEach((folderName: string) => {
            const folderPath = path.join(
              configManager?.getLocal().folderPath,
              folderName
            ); // 构建文件夹路径

            // 使用 fs 模块的 mkdir 方法来创建文件夹
            fs.mkdir(folderPath, { recursive: true }, (err) => {
              if (err) {
                console.error(`无法创建文件夹 ${folderPath}:`, err);
              } else {
                console.log(`文件夹 ${folderPath} 创建成功`);
              }
            });
          });

          port.postMessage({
            items: [
              {
                taskId: res.data.taskId,
                busId: data.busId,
                pjId: data.pjId,
                coId: user.coId,
                pjName: data.projectName,
              },
            ],
          });

          _event.reply('downsuccess', {});
        }
      })
      .catch((err) => {
        console.log(err);
      });
  });

  if (configManager.getLocal().folderPath) {
    const macAddress = getMAC();
    log.info(`记录本机地址：${macAddress}`);
    setPathMacId({
      mid: user.mid,
      macAddress,
      storagePath: configManager.getLocal().folderPath,
    })
      .then((res) => {
        log.info(`记录本机地址mainid：${res.data}`);
        store.set('mainId', res.data);
      })
      .catch(() => {});
  }
  // 清除未完成任务
  // batchFailure({
  //   mid: user.mid,
  //   mainId: store.get('mainId'),
  // });
}
